from loguru import logger
from google.protobuf import empty_pb2
from goods_srv.model.models import Category
from goods_srv.proto import goods_pb2, goods_pb2_grpc


class CategoryServicer(goods_pb2_grpc.GoodsServicer):
    def category_model_to_dict(self, category):
        re = {}

        re["id"] = category.id
        re["name"] = category.name
        re["level"] = category.level
        re["parent"] = category.parent_category_id
        re["is_tab"] = category.is_tab

        return re

    @logger.catch
    def GetAllCategorysList(self, request: empty_pb2.Empty, context):
        # 商品的分类
        level1 = []
        level2 = []
        level3 = []

        category_list_rsp = goods_pb2.CategoryListResponse()
        category_list_rsp.total = Category.select().count()
        for category in Category.select():
            category_rsp = goods_pb2.CategoryInfoResponse()
            category_rsp.id = category.id
            category_rsp.name = category.name
            category_rsp.parentCategory = category.parent_category_id
            category_rsp.level = category.level
            category_rsp.isTab = category.is_tab

            category_list_rsp.data.append(category_rsp)

            if category.level == 1:
                level1.append(self.category_model_to_dict(category))
            elif category.level == 2:
                level2.append(self.category_model_to_dict(category))
            elif category.level == 3:
                level3.append(self.category_model_to_dict(category))

            # 整理数据
            for data3 in level3:
                for data2 in leve2:
                    if data3["parent"] == data2["id"]:
                        if "sub_category" not in data2:
                            data2["sub_category"] = [data3]
                        else: 
